package com.hxcoder.mail.service.impl;

import com.hxcoder.mail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @author hxcoder
 */
@Service
public class MailServiceImpl implements MailService {

    private final static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单文本的邮件
     */
    @Override
    public boolean send(String to, String subject, String content) {
        logger.info("++++++++++++++++ 开始发送邮件验证码 ++++++++++++++++++");

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 邮件发送来源
        simpleMailMessage.setFrom(mailProperties.getUsername());
        // 邮件发送目标
        simpleMailMessage.setTo(to);
        // 设置标题
        simpleMailMessage.setSubject(subject);
        // 设置内容
        simpleMailMessage.setText(content);

        try {
            javaMailSender.send(simpleMailMessage);
            logger.info("++++++++++ 发送成功 ++++++++++++++");
            return true;
        } catch (Exception e) {
            logger.error("++++++++++ 发送失败 ++++++++++++++", e);
            return false;
        }
    }
}
